package utils;


import android.app.Activity;
import android.content.Context;
import android.widget.Toast;

import com.google.gson.Gson;

import student.andlei.com.student.BuildConfig;
import student.andlei.com.student.R;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import Dailog.CustomProgressDialog;
import application.App;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.Result;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import service.RetrofitGetService;
import service.RetrofitPostJsonService;
import service.RetrofitUpQmService;

import static utils.DensityUtil.shaEncode;


public class NetUtils {
    private Context context;

    public NetUtils(Context context) {
        this.context = context;
    }

    /**
     * 加载提示框
     */
    private CustomProgressDialog customProgressDialog;
    public static String token ="";
    private Map<String, String> headerParams;
    public final static String ImgHost ="http://123.56.113.213:1152/";
            //"http://dongli.qiantongtech.com/" ;
             //"http://123.56.113.213:1152/"
    /**
     * 初始化请求头，具体情况根据需求设置
     */
    public void initHeader() {

        headerParams = new HashMap<>();
        token = SPUtils.getInstance(context).getString("token");
        Logger.i("token--->",token);
        headerParams.put("authorization", ""+token);
    }
    /**
     * 初始化请求头，具体情况根据需求设置
     */
    public void initphotoHeader() {

        headerParams = new HashMap<>();
        // 传参方式为json
        headerParams.put("Content-Type", "application/json");


    }
    /**
     * 初始化数据
     *
     * @param action 当前请求的尾址
     */
    private Retrofit initBaseData(final String action) {
        // 监听请求条件
        final OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10, TimeUnit.SECONDS);

        builder.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("authorization",token).addHeader("User-Agent", "Mozilla/4.0").addHeader("Content-Type", "application/json").build();
//.newBuilder().addHeader("timesign",rs).build()
                Logger.i("zzz", "request====" + action);
                Logger.i("zzz", "request====" + request.headers().toString());
                Logger.i("zzz", "request====" + request.toString());
                okhttp3.Response proceed = chain.proceed(request);
                Logger.i("zzz", "proceed====" + proceed.headers().toString());
                return proceed;
            }
        });

        Retrofit.Builder builder1 = new Retrofit.Builder()
                .client(builder.build())                                    // 配置监听请求
                .addConverterFactory(GsonConverterFactory.create())         // 请求结果转换（当前为GSON）
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()); // 请求接受工具（当前为RxJava2）
        builder1.baseUrl(BuildConfig.BASE_URL + action.substring(0, action.lastIndexOf("/") + 1));

        return builder1.build();

    }
    /**
     * 初始化数据
     *
     * @param action 当前请求的尾址
     */
    private Retrofit initPhotoBaseData(final String action) {
        // 监听请求条件
        final OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(10, TimeUnit.SECONDS);

        builder.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder().addHeader("authorization",token).addHeader("User-Agent", "Mozilla/4.0").addHeader("Content-Type", "application/json").build();
//.newBuilder().addHeader("timesign",rs).build()
                Logger.i("zzz", "request====" + action);
                Logger.i("zzz", "request====" + request.headers().toString());
                Logger.i("zzz", "request====" + request.toString());
                okhttp3.Response proceed = chain.proceed(request);
                Logger.i("zzz", "proceed====" + proceed.headers().toString());
                return proceed;
            }
        });

        Retrofit.Builder builder1 = new Retrofit.Builder()
                .client(builder.build())                                    // 配置监听请求
                .addConverterFactory(GsonConverterFactory.create())         // 请求结果转换（当前为GSON）
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()); // 请求接受工具（当前为RxJava2）
        builder1.baseUrl("http://qixi.banyuekj.com/student_api/common/" + action.substring(0, action.lastIndexOf("/") + 1));

        return builder1.build();

    }
    /**
     * Get请求
     *
     * @param action   请求接口的尾址
     * @param params   索要传递的参数
     * @param observer 求情观察者
     */
    public void get(final String action, Map<String, String> params, Observer<ResponseBody> observer) {
        initHeader();
        RetrofitGetService getService = initBaseData(action).create(RetrofitGetService.class);
        if (params == null) {
            params = new HashMap<>();
        }

        Map<String, String> headerParams = new HashMap<>();
        headerParams.put("USER_TOKEN", "aaa");
        headerParams.put("DEVICE_ID", "bbbbb");
        headerParams.put("Content-Type", "application/json");
        headerParams.put("SYSTEM_NAME", "smallPlace");

        Logger.i("zzz", "request====" + new JSONObject(params));

        getService.getResult(action.substring(action.lastIndexOf("/") + 1), headerParams, params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * Post请求
     *
     * @param action   请求接口的尾址
     * @param observer 求情观察者
     */
    public void post(final String action, Map params, Observer<ResponseBody> observer) {
        initHeader();
        RetrofitPostJsonService jsonService = initBaseData(action).create(RetrofitPostJsonService.class);

        Logger.i("zzz", "request====" + params);
        String str1 = null;
        String timeStamp = String.valueOf(DateUtils.getStringToDate(DateUtils.getCurrentDate()));
        try {

            str1 = shaEncode(timeStamp+"qixi_LSDldf!jeisi2#*CX@3920");

        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,Object> map =new HashMap<String,Object>();
        map.put("timeStamp",timeStamp);
        map.put("sign",str1);
        map.put("params",params);

        RequestBody requestBody =
                RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                        new Gson().toJson(map));

        Logger.i("zzz", "request====" + new Gson().toJson(map));

        jsonService.postResult(action.substring(action.lastIndexOf("/") + 1), requestBody)
                .subscribeOn(Schedulers.newThread())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);


    }
    /**
     * 上传图片
     * create by weiang at 2016/5/20 17:33.
     */
    //String satisfaction,String attitude,String speed,String scorecomment,,String orderid,String satisfaction,String attitude,String speed,String scorecomment,
    public void upLoadImg(final String action,List<String> pathList, final Activity context) {
        initphotoHeader();
        RetrofitUpQmService retrofitUpQmService =  initPhotoBaseData(action).create(RetrofitUpQmService.class);
        showLoadDialog(context);
        String str1 = null;
        String timeStamp = String.valueOf(DateUtils.getStringToDate(DateUtils.getCurrentDate()));
        try {

            str1 = shaEncode(timeStamp+"qixi_LSDldf!jeisi2#*CX@3920");

        } catch (Exception e) {
            e.printStackTrace();
        }
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//表单类型
                .addFormDataPart("timeStamp", timeStamp)//ParamKey.TOKEN 自定义参数key常量类，即参数名
                .addFormDataPart("sign", str1);//ParamKey.TOKEN 自定义参数key常量类，即参数名
//                .addFormDataPart("attitude", attitude)//ParamKey.TOKEN 自定义参数key常量类，即参数名
//                .addFormDataPart("speed", speed)//ParamKey.TOKEN 自定义参数key常量类，即参数名
//                .addFormDataPart("scorecomment", scorecomment);//ParamKey.TOKEN 自定义参数key常量类，即参数
        //多张图片
        for (int i = 0; i < pathList.size(); i++) {
            File file = new File(pathList.get(i));//filePath 图片地址
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            builder.addFormDataPart("file", file.getName(), imageBody);//"imgfile"+i 后台接收图片流的参数名
        }

        List<MultipartBody.Part> parts = builder.build().parts();
        retrofitUpQmService.uploadQm(action,parts).enqueue(new Callback<Result<String>>() {//返回结果
            @Override
            public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                Toast.makeText(context,"评价成功",Toast.LENGTH_LONG).show();

                //context.finish();
                hideLoadDialog();
            }

            @Override
            public void onFailure(Call<Result<String>> call, Throwable t) {
                Toast.makeText(context,"评价失败",Toast.LENGTH_LONG).show();
                hideLoadDialog();
            }
        });
    }
    //
    public void  uploadQm(final String action, String orderid,String listgoodsid,String listcount, List<String> pathList, final Activity context, final boolean aBoolean){
        initphotoHeader();
        RetrofitUpQmService retrofitUpQmService =  initPhotoBaseData(action).create(RetrofitUpQmService.class);
        showLoadDialog(context);
        File file = new File(pathList.get(0));//filePath 图片地址
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
       // MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("MultipartFile", file.getName(), imageBody);
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//表单类型
                .addFormDataPart("orderid", orderid)//ParamKey.TOKEN 自定义参数key常量类，即参数名
                .addFormDataPart("listgoodsid",listgoodsid)
                .addFormDataPart("listcount",listcount)
                .addFormDataPart("MultipartFile", file.getName(), imageBody);
        List<MultipartBody.Part> parts = builder.build().parts();
        retrofitUpQmService.uploadQm(action,parts).enqueue(new Callback<Result<String>>() {
            @Override
            public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                if(response.code()==200){

                    System.out.print(response.body().toString());
                    Toast.makeText(context,"签收成功",Toast.LENGTH_LONG).show();
                    if(aBoolean){
                        context.finish();
                    }
                }else {
                    Toast.makeText(context,"签收失败",Toast.LENGTH_LONG).show();
                }
                hideLoadDialog();
            }

            @Override
            public void onFailure(Call<Result<String>> call, Throwable t) {
                Toast.makeText(context,"签收失败",Toast.LENGTH_LONG).show();
                hideLoadDialog();
            }
        });
    }
    /**
     * 显示加载提示框
     */
    public void showLoadDialog(Activity activity) {
                customProgressDialog = new CustomProgressDialog(activity, R.style.progress_dialog_loading, "加载中...");
                customProgressDialog.show();

    }
    /**
     * 隐藏加载提示框
     */
    public void hideLoadDialog() {
                if (customProgressDialog != null && customProgressDialog.isShowing()) {
                    customProgressDialog.dismiss();
                }

    }
}
